from datetime import datetime

from flask import Blueprint, g, render_template, request
from flask_wtf import FlaskForm
from wtforms import HiddenField, StringField, SelectField, SubmitField
from wtforms.validators import DataRequired

from blueprint.grade import GradeModel
from exts import db

# 创建用户蓝图对象
student_bp = Blueprint('student', __name__, url_prefix='/student')


class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age


class StudentModel(db.Model):
    """
    学生模型
    """
    __tablename__ = "t_student"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)  # 主键id
    name = db.Column(db.String(50), nullable=False)  # 学生名称
    remark = db.Column(db.Text)  # 备注
    grade_id = db.Column(db.Integer, db.ForeignKey('t_grade.id'))  # 年级外键id
    grade = db.relationship('GradeModel')  # 建立外键关联


class StudentForm(FlaskForm):
    id = HiddenField()
    name = StringField('学生姓名', render_kw={'placeholder': '请输入学生姓名'}, validators=[DataRequired()])
    grade = SelectField('年级', choices=[], validators=[DataRequired()])
    submit = SubmitField("提交")


titleA = 'student'
timeA = datetime.now()


@student_bp.route('/list')
def list():
    studentList = StudentModel.query.all()
    return render_template('student/list.html', studentList=studentList)


@student_bp.route('/index')
def index():
    print(g.get('username'))
    return '主页'


@student_bp.route('/add', methods=['GET', 'POST'])
def add():
    studentForm = StudentForm()
    if request.method == 'GET':
        # 加载年级下拉框数据
        gradeList = GradeModel.query.all()
        gradeChoices = [('', '请选择年级')] + [(grade.id, grade.name) for grade in gradeList]
        studentForm.grade.choices = gradeChoices
        return render_template('student/add.html', form=studentForm)
    else:
        data = studentForm.data
        print('data:', data)
        print(data['name'])
        studentModel = StudentModel(name=data['name'], grade_id=data['grade'])
        db.session.add(studentModel)
        db.session.commit()
        return list()


@student_bp.route('/update', methods=['GET', 'POST'])
def update():
    studentForm = StudentForm()
    if request.method == 'GET':
        gradeList = GradeModel.query.all()
        studentForm.grade.choices = [('', '请选择年级')] + [(grade.id, grade.name)
                                                            for grade in gradeList]
        id = request.args.get('id', type=int)
        student = StudentModel.query.get(id)
        studentForm.grade.default = student.grade_id
        studentForm.process()  # 让默认值设置生效
        studentForm.id.data = student.id
        studentForm.name.data = student.name
        return render_template('student/update.html', form=studentForm)
    else:
        data = studentForm.data
        print('data:', data)
        print(data['id'])
        student = StudentModel.query.get(data['id'])
        student.name = data['name']
        student.grade_id = data['grade']
        db.session.commit()
        return list()


@student_bp.route('/delete/<int:id>')
def delete(id):
    student = StudentModel.query.get(id)
    db.session.delete(student)
    db.session.commit()
    return list()
